<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="拼团名称" prop="groupName">
        <el-input
          v-model="queryParams.groupName"
          placeholder="请输入拼团名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['market:groupbuying:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="groupbuyingList">
      <el-table-column label="拼团名称" align="center" prop="groupName" />
      <el-table-column label="开始时间" align="center" prop="startTime"  />
      <el-table-column label="结束时间" align="center" prop="endTime"  />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateGoods(scope.row)"
            v-hasPermi="['market:groupbuying:edit']"
          >编辑商品</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['market:groupbuying:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['market:groupbuying:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改拼团管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="拼团名称" prop="groupName">
          <el-input v-model="form.groupName" placeholder="请输入拼团名称" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker style="width: 100%" clearable size="small"
            v-model="form.startTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker style="width: 100%" clearable size="small"
            v-model="form.endTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 编辑商品对话框 -->
    <el-dialog :title="title" :visible.sync="goodsOpen" width="1070px" append-to-body>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleGoodsEdit"
          >新增商品</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDeleteGoods"
          >批量删除</el-button>
        </el-col>
      </el-row>
      <el-table  :data="goodsList" @selection-change="handleGoodsSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="商品信息" align="center" width="370" >
          <template slot-scope="scope">
            <div style="height: 100%">
              <div style="display: inline-block;float:left;width: 80px;height: 80px"  >
                <el-image :src="baseUrl+scope.row.picturePath"></el-image>
              </div>
              <div style="display: inline-block;float:left;margin-left: 15px;height: 100%;width: 250px">
                <div style="text-align: left">{{scope.row.goodsCode}}</div>
                <div style="text-align: left">{{scope.row.goodsName}}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="售价" align="center" prop="referencePrice"/>
        <el-table-column label="拼购价" width="120" align="center" prop="groupPrice">
          <template slot-scope="scope">
            {{scope.row.groupPrice}}
            <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdatePrice(scope.row)"
            v-hasPermi="['goods:goods:edit']"
          >编辑</el-button>
          </template>
        </el-table-column>
        <el-table-column label="主页显示" align="center" prop="isShow">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.isShow"
              active-value="0"
              inactive-value="1"
              @change="handleIsShowChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="库存" align="center" prop="stock" />
        <el-table-column label="排序" align="center" prop="sort" />
        <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-top"
              @click="handleMoveUpGoods(scope.row)"
            >上移</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-bottom"
              @click="handleMoveDownGoods(scope.row)"
            >下移</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDeleteGoods(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="goodsTotal>0"
        :total="goodsTotal"
        :page.sync="queryGoodsParams.pageNum"
        :limit.sync="queryGoodsParams.pageSize"
        @pagination="getGroupGoodsList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel">确 定</el-button>
      </div>
    </el-dialog>

    <!--    编辑价格弹窗-->
    <el-dialog :title="title" :visible.sync="price" width="800px" append-to-body>
      <el-form ref="priceForm" :model="priceForm" :rules="rules"  label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品名称" >
              <b>{{priceForm.name}}</b>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="拼购价" >
              <el-input v-model="groupGoodsForm.groupPrice"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-table :data="priceForm.unitsList" border  style="width: 100%">
              <el-table-column v-if="priceForm.unitsList && priceForm.unitsList[0] && priceForm.unitsList[0].goodsUnit"   prop="goodsUnit" label="规格" width="">
                <template slot-scope="scope">
                  {{unitFormat(scope.row.goodsUnit)}}
                </template>
              </el-table-column>
              <el-table-column  prop="price" label="售价"  >
                <template slot-scope="scope">
                  {{scope.row.price}}
                </template>
              </el-table-column>
              <el-table-column  prop="groupPrice" label="拼购价">
                <template slot-scope="scope">
                  <el-form-item label-width="0" style="margin-bottom: 0" :prop="'unitsList.' + scope.$index + '.groupPrice'" :rules='{ required: true,pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,message: "请输入正确金额,必须是数字型,且小数位最多保留两位！",trigger: "blur" }'>
                    <el-input v-model="scope.row.groupPrice"/>
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPriceForm">确 定</el-button>
        <el-button @click="priceCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 商品选择器 -->
    <goods-selector
      ref="goodsSelector"
      :open="goodsSelector"
      :multiple="-1"
      @input="getCheckedGoods"
      @close="closeSelector"
    ></goods-selector>

  </div>
</template>

<script>
import {
  listGroupbuying,
  getGroupbuying,
  delGroupbuying,
  addGroupbuying,
  updateGroupbuying,
  changeGroupbuyingStatus
} from "@/api/market/groupbuying";
import GoodsSelector from "@/views/goods/goods/goodsSelector";
import {
  addGroupGoods,
  changeGroupGoodsStatus,
  delGroupGoods, getGroupGoods,
  listGroupGoods,
  moveDownGoods,
  moveUpGoods, updateGroupGoods
} from "@/api/market/groupGoods";
import {getGoods, updateGoodsPriceStock} from "@/api/goods/goods";

export default {
  name: "Groupbuying",
  components: {
    GoodsSelector
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 拼团管理表格数据
      groupbuyingList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      goodsOpen:false,
      ids:[],
      goodsList:[],
      multiple:false,
      baseUrl:process.env.VUE_APP_BASE_API,
      goodsTotal: 0,
      goodsSelector:false,
      queryGoodsParams: {
        pageNum: 1,
        pageSize: 10,
        groupId:null
      },
      price:false,
      priceForm:{},
      groupGoodsForm:{},
      // 状态：0为启用，1为停用字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        groupName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        groupName: [
          { required: true, message: "拼团名称不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("store_common_status").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    /** 查询拼团管理列表 */
    getList() {
      this.loading = true;
      listGroupbuying(this.queryParams).then(response => {
        this.groupbuyingList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.goodsOpen = false;
      this.reset();
    },
    priceCancel(){
      this.price = false;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        extAppid: null,
        groupName: null,
        startTime: null,
        endTime: null,
        status: "1"
      };
      this.resetForm("form");
      this.groupGoodsForm = {
        id: null,
        groupId: null,
        goodsId: null,
        groupPrice: null,
        isShow: null,
        sort: null
      };
      this.priceForm = {
        id: null,
        extAppid: null,
        goodsCode: null,
        name: null,
        video: null,
        videoPath:null,
        picFileList: [],
        goodsClassId: null,
        referencePrice: null,
        unitsList:[],
        //选中的规格
        unitsKeys:[],
        unitsValues:[],
        status: "1",
        content: null,
        attributeValueList:[],
        templateId: null
      };
      this.resetForm("priceForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加拼团管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id
      getGroupbuying(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改拼团管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateGroupbuying(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGroupbuying(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id ;
      this.$confirm('是否确认删除拼团管理编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delGroupbuying(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 修改状态 */
    handleStatusChange(row){
      let text = row.status === "0" ? "启用" : "停用";
      this.$confirm('确认要"' + text + '""' + row.groupName + '"拼购吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return changeGroupbuyingStatus(row.id, row.status);
      }).then(() => {
        this.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    handleUpdateGoods(row){
      this.queryGoodsParams.groupId = row.id;
      this.getGroupGoodsList();
      this.title = "拼购商品管理"
      this.goodsOpen = true;
    },
    handleGoodsEdit(){
      this.goodsSelector=true;
    },

    /** 删除按钮操作 */
    handleDeleteGoods(row) {
      const ids = row.id || this.ids ;
      this.$confirm('是否确认删除选中的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delGroupGoods(ids);
      }).then(() => {
        this.getGroupGoodsList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 多选框选中数据
    handleGoodsSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.multiple = !selection.length
    },
    getGroupGoodsList(){
      listGroupGoods(this.queryGoodsParams).then(response => {
        this.goodsList = response.rows;
        this.goodsTotal = response.total;
      });
    },
    //选择器确定选择
    getCheckedGoods(checkedGoodsList){
      let groupGoods = [];
      checkedGoodsList.forEach(goods=>{
        let form = {
          id: null,
          groupId: this.queryGoodsParams.groupId,
          goodsId: goods.id,
          groupPrice: goods.referencePrice,
          isShow: '1',
          sort: null
        }
        groupGoods.push(form)
      })
      //添加数据
      if(groupGoods.length > 0 ){
        addGroupGoods(groupGoods).then(response => {
          this.msgSuccess("新增成功");
          this.getGroupGoodsList();
        })
      }
    },
    closeSelector(){
      this.goodsSelector=false;
    },
    handleMoveUpGoods(row){
      if(row.sort == 1){
        return
      }
      moveUpGoods(row).then(response =>{
        this.getGroupGoodsList();
      })

    },
    handleMoveDownGoods(row){
      if(row.sort == this.goodsTotal){
        return
      }
      const form = row;
        moveDownGoods(form).then(response =>{
        this.getGroupGoodsList();
      })
    },
    /** 修改主页显示状态 */
    handleIsShowChange(row){
      let text = row.isShow === "0" ? "显示" : "隐藏";
      this.$confirm('确认要"' + text + '""' + row.goodsName + '"拼购商品吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return changeGroupGoodsStatus(row.id, row.isShow);
      }).then(() => {
        this.msgSuccess(text + "成功");
      }).catch(function() {
        row.isShow = row.isShow === "0" ? "1" : "0";
      });
    },
    handleUpdatePrice(row){
      this.reset();
      const id = row.goodsId;
      getGroupGoods(row.id).then(res =>{
        this.groupGoodsForm=res.data;
      })
      getGoods(id).then(response => {
        this.priceForm = response.data;
        this.price = true;
        this.title = "编辑拼团价格";
      });
    },
    submitPriceForm() {
      this.$refs["priceForm"].validate(valid => {
        if (valid) {
          updateGroupGoods(this.groupGoodsForm);
          updateGoodsPriceStock(this.priceForm).then(response => {
            this.msgSuccess("修改成功");
            this.price=false;
            this.getGroupGoodsList();
          });
        }
      });
    },
    unitFormat(obj){
      let str = ''
      if(obj){
        let a = Object.values(JSON.parse(obj));
        a.forEach(value => {
          str+=value+"/";
        })
      }
      return str;
    },
  }
};
</script>
